<script setup lang="ts">
import { reactive, ref, toRaw } from "vue";
import { onLoad, onPageScroll, onReachBottom } from "@dcloudio/uni-app";
import { useList } from "@/hooks/page";
import { header_api, index_api } from "@/package/community/api/guider_group";
import { AppData } from "@/utils/app";
import { Account } from "@/utils/account";
import { Router } from "@/utils/router";

import PageSticky from "@/components/page/sticky.vue";
import IndexSearchBar from "./components/index-search-bar.vue";
import IndexTabItem from "./components/index-tab-item.vue";
import IndexGroupItem from "./components/index-group-item.vue";
import ListMore from "@/components/list/more.vue";
import PopupModal from "@/components/popup/modal.vue";

onLoad(() => {
  header_api().then((resp) => {
    typeList.value = resp.cate_arr;
    provinceList.value = resp.in_china_arr;
    countryList.value = resp.out_china_arr;
  });

  reloadList();
});
onPageScroll(() => (listLoadMore.value = listData.value.length > 1));
onReachBottom(() => loadMoreList());

const queryData = reactive({
  keyword: "",
  cate_id: 0,
  province_id: "",
  country_id: "",
});

const searchStatus = ref<"init" | "finish">("init"); // search：搜索中（聚焦）, finish：搜索完成
const searchClick = (type: "search" | "clear") => {
  if (type === "search") {
    const keyword = queryData.keyword.trim();
    if (!keyword) return;

    queryData.cate_id = 0;
    queryData.province_id = "";
    queryData.country_id = "";
    reloadList().then(() => (searchStatus.value = "finish"));
  } else {
    queryData.keyword = "";
    searchStatus.value = "init";
    reloadList();
  }
};

const typeList = ref<any[]>([]);
const typeClick = (id: number) => {
  queryData.cate_id = id;
  reloadList();
};
const tabIndex = ref(-1);
const tabClick = (index: number) => {
  tabIndex.value = index === tabIndex.value ? -1 : index;
};
const provinceList = ref<any[]>([]);
const provinceClick = (id: string) => {
  queryData.province_id = id;
  queryData.country_id = "";
  reloadList();
  tabIndex.value = 0;
};
const countryList = ref<any[]>([]);
const countryClick = (id: string) => {
  queryData.country_id = id;
  queryData.province_id = "";
  reloadList();
  tabIndex.value = 1;
};

const { listData, listStatus, listLoadMore, reloadList, loadMoreList } =
  useList({ page: 1, page_size: 10 }, (query) => {
    return index_api({ ...query, ...toRaw(queryData) });
  });

const groupClick = (index: number) => {
  const group = listData.value[index];

  const fn = (isLogin: boolean) => {
    Router.navigateToOrRedirectTo(
      isLogin,
      `/package/community/pages/group/detail?id=${group.id}`
    );
  };

  // VIP 群
  group.is_vip === 1
    ? Account.checkLogin((isLogin) => {
        // 是 VIP
        if (AppData.userData.is_vip_member === 1) return fn(isLogin);

        isLogin && Router.navigateBack();
        popupModal.value?.show(
          {
            title: "VIP专属群",
            content:
              "该群为认证导游VIP权益包专属群，您未购买权益包，是否前往购买？",
            confirmText: "去购买",
          },
          () => {
            Router.navigateTo("/package/mall/pages/vip/index");
          }
        );
      })
    : fn(false);
};

const popupModal = ref<InstanceType<typeof PopupModal>>();
</script>

<template>
  <PageSticky>
    <IndexSearchBar v-model="queryData.keyword" @search="searchClick" />
    <view class="index-line"></view>

    <scroll-view
      class="index-type"
      v-if="searchStatus === 'init'"
      scroll-x
      enhanced
      :show-scrollbar="false"
    >
      <view class="index-type-space"></view>
      <view
        class="index-type-item"
        :class="{ 'index-type-active': queryData.cate_id === i.id }"
        v-for="i of typeList"
        :key="i.id"
        @click="typeClick(i.id)"
      >
        {{ i.name }}
      </view>
    </scroll-view>
  </PageSticky>

  <view class="index-tab" v-if="searchStatus === 'init'">
    <view class="index-tab-item" @click="tabClick(0)">
      <IndexTabItem :isActive="tabIndex === 0" text="国内" />
    </view>
    <scroll-view
      class="index-tab-wrapper"
      :style="{ height: tabIndex === 0 ? ' calc(100% - 200rpx)' : 0 }"
      scroll-y
      enhanced
      :show-scrollbar="false"
    >
      <view
        class="index-tab-option"
        :class="{
          'index-tab-active': queryData.province_id === i.province_id,
        }"
        v-for="i of provinceList"
        :key="i.province_id"
        @click="provinceClick(i.province_id)"
      >
        {{ i.count ? `${i.name}(${i.count})` : i.name }}
      </view>
      <view class="index-tab-safe"></view>
    </scroll-view>

    <view class="index-tab-item" @click="tabClick(1)">
      <IndexTabItem :isActive="tabIndex === 1" text="海外" />
    </view>
    <scroll-view
      class="index-tab-wrapper"
      :style="{ height: tabIndex === 1 ? ' calc(100% - 200rpx)' : 0 }"
      scroll-y
      enhanced
      :show-scrollbar="false"
    >
      <view
        class="index-tab-option"
        :class="{ 'index-tab-active': queryData.country_id === i.country_id }"
        v-for="i of countryList"
        :key="i.country_id"
        @click="countryClick(i.country_id)"
      >
        {{ i.count ? `${i.name}(${i.count})` : i.name }}
      </view>
      <view class="index-tab-safe"></view>
    </scroll-view>
  </view>

  <view
    class="index-data"
    :style="{ paddingLeft: searchStatus === 'init' ? '180rpx' : 0 }"
  >
    <view class="index-data-wrapper">
      <view
        class="index-data-item"
        v-for="(i, d) of listData"
        :key="i.id"
        :style="{ marginLeft: searchStatus === 'init' ? '20rpx' : '50rpx' }"
        @click="groupClick(d)"
      >
        <IndexGroupItem :info="i" />
      </view>
    </view>

    <ListMore v-if="listLoadMore" :status="listStatus" />
  </view>

  <PopupModal ref="popupModal" />
</template>

<style lang="scss">
page {
  background-color: #ffffff;
}

.index-line {
  border-bottom: 2rpx solid #f1f1f1;
}

.index-type {
  height: 108rpx;
  white-space: nowrap;

  .index-type-space,
  .index-type-item {
    display: inline-block;
    vertical-align: top;
  }

  .index-type-space {
    width: 30rpx;
  }

  .index-type-item {
    padding: 0 24rpx;
    margin-top: 28rpx;
    margin-right: 30rpx;
    font-size: 26rpx;
    color: #666666;
    line-height: 48rpx;
    border-radius: 30rpx;
    border: 2rpx solid #f3f3f3;
    background-color: #f3f3f3;
  }

  .index-type-active {
    color: #ff7900;
    border-color: #ff7900;
    background-color: #fff7ef;
  }
}

.index-tab {
  position: fixed;
  left: 0;
  top: 220rpx;
  bottom: 0;
  width: 180rpx;
  background-color: #f6f7f8;

  .index-tab-item {
    background-color: #ffffff;
  }

  .index-tab-wrapper {
    // height: calc(100% - 200rpx);
    transition: all 0.3s ease-out;
  }

  .index-tab-option {
    font-size: 28rpx;
    color: #999999;
    line-height: 100rpx;
    text-align: center;
    background-color: #ffffff;
  }

  .index-tab-active {
    color: #ff7900;
  }
}

.index-data {
  .index-data-wrapper {
    padding-top: 20rpx;
  }

  .index-data-item {
    margin-right: 30rpx;
    margin-bottom: 20rpx;
  }
}
</style>